<template>
  <div class="admin-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>后台管理</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 信息审核 -->
        <el-tab-pane label="信息审核" name="itemAudit">
          <el-table :data="itemList" v-loading="itemLoading">
            <el-table-column prop="infoNo" label="信息编号" width="150" />
            <el-table-column label="类型" width="80">
              <template #default="{ row }">
                <el-tag :type="row.type === 0 ? 'warning' : 'success'">
                  {{ row.type === 0 ? '失物' : '招领' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="itemName" label="物品名称" width="120" />
            <el-table-column prop="description" label="物品描述" show-overflow-tooltip />
            <el-table-column label="发布时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="{ row }">
                <el-button type="success" link @click="auditItem(row.id, 1)">通过</el-button>
                <el-button type="danger" link @click="showRejectDialog(row.id)">驳回</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 认领审核 -->
        <el-tab-pane label="认领审核" name="claimAudit">
          <el-table :data="claimList" v-loading="claimLoading">
            <el-table-column prop="requestNo" label="申请编号" width="180" />
            <el-table-column prop="applicantName" label="申请人" width="120" />
            <el-table-column prop="claimReason" label="认领理由" show-overflow-tooltip />
            <el-table-column label="申请时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="{ row }">
                <el-button type="success" link @click="auditClaim(row.id, 1)">通过</el-button>
                <el-button type="danger" link @click="showRejectClaimDialog(row.id)">驳回</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 公告管理 -->
        <el-tab-pane label="公告管理" name="announcement">
          <el-button type="primary" @click="showAnnouncementDialog" style="margin-bottom: 20px">
            <el-icon><Plus /></el-icon>
            发布公告
          </el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 驳回信息对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回信息" width="500px">
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="驳回理由">
          <el-input 
            v-model="rejectForm.comment" 
            type="textarea" 
            :rows="4"
            placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRejectItem">确定</el-button>
      </template>
    </el-dialog>

    <!-- 驳回认领对话框 -->
    <el-dialog v-model="rejectClaimDialogVisible" title="驳回认领" width="500px">
      <el-form :model="rejectClaimForm" label-width="100px">
        <el-form-item label="驳回理由">
          <el-input 
            v-model="rejectClaimForm.comment" 
            type="textarea" 
            :rows="4"
            placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectClaimDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRejectClaim">确定</el-button>
      </template>
    </el-dialog>

    <!-- 发布公告对话框 -->
    <el-dialog v-model="announcementDialogVisible" title="发布公告" width="600px">
      <el-form :model="announcementForm" :rules="announcementRules" ref="announcementFormRef" label-width="100px">
        <el-form-item label="公告类型" prop="type">
          <el-radio-group v-model="announcementForm.type">
            <el-radio :label="0">普通通知</el-radio>
            <el-radio :label="1">紧急通知</el-radio>
            <el-radio :label="2">系统通知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input 
            v-model="announcementForm.content" 
            type="textarea" 
            :rows="6"
            placeholder="请输入公告内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="announcementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePublishAnnouncement">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getItemList, auditItem as auditItemApi } from '@/api/item'
import { getPendingClaims, auditClaim as auditClaimApi } from '@/api/claim'
import { publishAnnouncement } from '@/api/announcement'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const activeTab = ref('itemAudit')

const itemLoading = ref(false)
const itemList = ref([])

const claimLoading = ref(false)
const claimList = ref([])

const rejectDialogVisible = ref(false)
const rejectForm = reactive({
  id: null,
  comment: ''
})

const rejectClaimDialogVisible = ref(false)
const rejectClaimForm = reactive({
  id: null,
  comment: ''
})

const announcementDialogVisible = ref(false)
const announcementFormRef = ref(null)
const announcementForm = reactive({
  type: 0,
  title: '',
  content: '',
  publisherId: userStore.userInfo.userId
})

const announcementRules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 100, message: '公告内容至少100字', trigger: 'blur' }
  ]
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString()
}

const auditItem = async (id, status) => {
  try {
    await auditItemApi({ id, status, auditComment: '审核通过' })
    ElMessage.success('审核成功')
    loadPendingItems()
  } catch (error) {
    console.error(error)
  }
}

const showRejectDialog = (id) => {
  rejectForm.id = id
  rejectForm.comment = ''
  rejectDialogVisible.value = true
}

const handleRejectItem = async () => {
  if (!rejectForm.comment) {
    ElMessage.warning('请输入驳回理由')
    return
  }
  try {
    await auditItemApi({ id: rejectForm.id, status: 4, auditComment: rejectForm.comment })
    ElMessage.success('驳回成功')
    rejectDialogVisible.value = false
    loadPendingItems()
  } catch (error) {
    console.error(error)
  }
}

const auditClaim = async (id, status) => {
  try {
    await auditClaimApi({ id, status, auditComment: '审核通过' })
    ElMessage.success('审核成功')
    loadPendingClaims()
  } catch (error) {
    console.error(error)
  }
}

const showRejectClaimDialog = (id) => {
  rejectClaimForm.id = id
  rejectClaimForm.comment = ''
  rejectClaimDialogVisible.value = true
}

const handleRejectClaim = async () => {
  if (!rejectClaimForm.comment) {
    ElMessage.warning('请输入驳回理由')
    return
  }
  try {
    await auditClaimApi({ id: rejectClaimForm.id, status: 2, auditComment: rejectClaimForm.comment })
    ElMessage.success('驳回成功')
    rejectClaimDialogVisible.value = false
    loadPendingClaims()
  } catch (error) {
    console.error(error)
  }
}

const showAnnouncementDialog = () => {
  announcementForm.type = 0
  announcementForm.title = ''
  announcementForm.content = ''
  announcementDialogVisible.value = true
}

const handlePublishAnnouncement = () => {
  announcementFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await publishAnnouncement(announcementForm)
        ElMessage.success('发布成功')
        announcementDialogVisible.value = false
      } catch (error) {
        console.error(error)
      }
    }
  })
}

const loadPendingItems = async () => {
  itemLoading.value = true
  try {
    const res = await getItemList({ current: 1, size: 100 })
    itemList.value = res.data.records.filter(item => item.status === 0)
  } catch (error) {
    console.error(error)
  } finally {
    itemLoading.value = false
  }
}

const loadPendingClaims = async () => {
  claimLoading.value = true
  try {
    const res = await getPendingClaims({ current: 1, size: 100 })
    claimList.value = res.data.records
  } catch (error) {
    console.error(error)
  } finally {
    claimLoading.value = false
  }
}

onMounted(() => {
  loadPendingItems()
  loadPendingClaims()
})
</script>

<style scoped>
.admin-container {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>

